# coding=utf-8
"""
Routing queue
                  \*.orange.* -- Q1 -- C1
P -- X(topic) -- \
                  \lazy.# -- Q2 -- C2

一个消息能通过交换机发送到多个队列，发送机制是通过绑定在交换机上的队列关键字（关键字模糊匹配）
"""

import json
import pika


# 设置MQ环境
env = "pt_test"

if env == "localhost":
    mq_info = {
        "username": "guanfuchang",
        "password": "12345678",
        "host": "localhost",
        "virtual_host": "/vhost_qa"
    }
elif env == "pt_test":
    mq_info = {
        "username": "test",
        "password": "nD7hWdBiRM",
        "host": "mq.test.thinkinpower.net",
        "virtual_host": "test"
    }


def get_connection():
    """
    获取MQ连接
    :return:
    """
    # 连接MQ
    user_pwd = pika.PlainCredentials(username=mq_info.get("username"), password=mq_info.get("password"))
    connection = pika.BlockingConnection(pika.ConnectionParameters(host=mq_info.get("host"),
                                                                   virtual_host=mq_info.get("virtual_host"),
                                                                   credentials=user_pwd))
    return connection


# 获取MQ连接
connection = get_connection()

# 在连接上创建一个频道CHANNEL
channel = connection.channel()

# 创建模糊匹配类型的exchange。
channel.exchange_declare(exchange='rfchina.platform', exchange_type='topic', durable=True)

# 发送消息
data = {
    "amount": "82001",
    "batchNo": "SLW20190802907119847",
    "bizNo": "ST1201908021021300000337",
    "status": 3,
    "sysErrMsg": "该笔支付处理成功，客户记账成功",
    "transDate": "2019-08-02 10:22:03",
    "userErrMsg": "该笔支付处理成功，客户记账成功"
}
channel.basic_publish(exchange='rfchina.platform',  # 指明用于发布消息的交换机
                      routing_key='wallet.pay.result',  # 路由键，绑定关键字，将队列变成[warn]日志的专属队列
                      body=json.dumps(data,ensure_ascii=False)  # 生产者要发送的消息
                      )
print("[生产者] send %s'" %json.dumps(data,ensure_ascii=False))

connection.close()  # 当生产者发送完消息后，可选择关闭连接
